import React, {useEffect, useState} from "react";
import {Button, Checkbox, Divider, Input, Space, Table} from "antd";
import {ColumnsType} from "antd/es/table";
import {
	ArrowLeftOutlined,
	DeleteOutlined,
	DownloadOutlined,
	FileTextFilled,
	FolderOpenFilled,
	PlusOutlined,
	UploadOutlined
} from "@ant-design/icons";
import styled from "@emotion/styled";
import useWindowSize from "@/hooks/useWindow";
import {CreateFile} from "@/pages/tools/components";
import {defaultFilePageProp, FileInfoProp, FilePageProp} from "@/pages/tools/modules";
import {useRequest} from "ahooks";
import {fileList} from "@/api/file";



const parentPath = (path: string): string => {
	let pos = path.lastIndexOf("/");
	let res = path.substr(0,pos);
	return res == "" ? "/" : res;
}

const FileName: React.FC<{prop: FileInfoProp, click: (path: string, isDir: boolean) => void}> = ({prop, click}) => {
	return <p style={{marginTop: 0, marginBottom: 0, cursor: 'pointer'}} onClick={() => click(prop.path, prop.isDir)}>
		{prop.isDir ? <FolderOpenFilled /> : <FileTextFilled />}&nbsp;&nbsp;
		{prop.isLink ? prop.name + ' ➞ ' + prop.linkPath : prop.name}
	</p>
}

export const ToolsFilePage = () => {

	const columns: ColumnsType<FileInfoProp> = [
		{
			title: '文件名',
			key: 'name',
			dataIndex: 'name',
			align: 'left',
			render: (text, record, index) => <FileName prop={record} click={() => setQueryParam({...queryParam, path: queryParam.path + '/' + record.name})} />
		},
		{
			title: '权限',
			key: 'perm',
			dataIndex: 'perm',
			align: 'center',
			render: (text) => <p style={{marginTop: 0, marginBottom: 0, color: '#2f54eb'}}>{text}</p>
		},
		{
			title: '用户',
			key: 'user',
			dataIndex: 'user',
			align: 'center',
			width: 100
		},
		{
			title: '用户组',
			key: 'group',
			dataIndex: 'group',
			align: 'center',
			width: 100
		},
		{
			title: '大小',
			key: 'size',
			dataIndex: 'size',
			align: 'center',
		},
		{
			title: '修改时间',
			key: 'updateTime',
			dataIndex: 'updateTime',
			align: 'center',
			width: 200
		},
		{
			title: '操作',
			key: 'active',
			align: 'center',
			width: 150,
			render: (text, record, index) => (
				<Space size={'small'}>

				</Space>
			),
		},
	];


	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [showCreate, setShowCreate] = useState(false);
	const {width, height} = useWindowSize()
	const [tableHeight, setTableHeight] = useState<number>(0);
	const [datasource, setDatasource] = useState<FileInfoProp[]>([]);
	const [total, setTotal] = useState<number>(0);
	const [queryParam, setQueryParam] = useState<FilePageProp>(defaultFilePageProp);

	const {loading, run} = useRequest(fileList, {
		manual: true,
		onSuccess: (data)=> {
			setDatasource(data.records);
			setTotal(data.total)
		}
	})

	const rowSelection = {
		onChange: (selectedRowKeys: React.Key[], selectedRows: FileInfoProp[]) => {
			console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
		},
		getCheckboxProps: (record: FileInfoProp) => ({
			disabled: record.name === 'Disabled User', // Column configuration not to be checked
			name: record.name,
		}),
	};

	const openFile = (path: string, isDir: boolean) => {
		if (isDir) {

		} else {

		}
	}

	const pageChange = (page: number, pageSize: number) => {
	}

	const onSearch = (value: string) => {

	};

	const closeDrawer = (isLoad: boolean) => {}

	const searchHandler = async (path: string) => {
		const query: FilePageProp = {...queryParam, path: path};
		await setQueryParam(query)
		await run(query);
	}

	useEffect(() => {
		run(queryParam);
	}, [queryParam])


	useEffect(() => {
		setTableHeight(height - 64 - 24 * 4)
		run(queryParam)
		return () => {
			setDatasource([])
			setQueryParam(defaultFilePageProp);
		}
	}, [])

	return <Container>
		<Space style={{marginBottom: 10}}>
			<Button type='primary' size="middle" icon={<PlusOutlined />} onClick={() => setShowCreate(true)}>创建</Button>
			<Button type='primary' size="middle" icon={<ArrowLeftOutlined />} onClick={() => openFile(parentPath(queryParam.path), true)}>上一层</Button>
			<Button type='primary' size="middle" icon={<UploadOutlined />}>上传</Button>
			<Button type='primary' size="middle" icon={<DownloadOutlined />}>下载</Button>
			<Button type='primary' size="middle" danger icon={<DeleteOutlined />}>删除</Button>
			<Divider type="vertical" />
			<Input.Search
				className="tools-search"
				addonBefore="路径"
				placeholder="请输入系统路径"
				enterButton="打开"
				size="middle"
				value={queryParam.path}
				onChange={value => searchHandler(value.target.value)}
				onSearch={(value) => openFile(value, true)}
			/>
			<Checkbox value={queryParam.showHidden} onChange={(e) => setQueryParam({...queryParam, showHidden: e.target.value as boolean})}>隐藏文件</Checkbox>
		</Space>
		<Table
			bordered
			size={'small'}
			columns={columns}
			loading={loading}
			dataSource={datasource}
			style={{ marginTop: 10 }}
			rowKey={(record) => record.name}
			pagination={{
				onShowSizeChange: (current, size) => run({...queryParam, page: current, size: size}),
				onChange: (page, pageSize) => run({...queryParam, page: page, size: pageSize}),
				showTotal: () => `共 ${total} 个`,
				showQuickJumper: true,
				showSizeChanger: true,
				pageSize: queryParam.size,
				current: queryParam.page,
				size: 'default',
				total: total,
			}}
			rowSelection={{
				type: 'checkbox',
				selectedRowKeys: selectedRowKeys,
				onChange: (selectedRowKeys: React.Key[], selectedRows: FileInfoProp[]) => {
					setSelectedRowKeys([...selectedRowKeys.map(item => item as string)])
				}
			}}
		/>
		<CreateFile open={showCreate} onCancel={closeDrawer} />
	</Container>
}

const Container = styled.div`
	.tools-search {
		input {
			width: 300px;
		}
	}
`